import JSEncrypt from 'jsencrypt'

export const objectToHttpQuery = data => {
  let ret = ''
  for (const key in data) {
    const value = data[key]
    ret += `${encodeURIComponent(key)}=${encodeURIComponent(value)}&`
  }
  return ret.substring(0, ret.length - 1)
}

export const encrypt = (plainString, publicKey) => {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey)
  return encryptor.encrypt(plainString)
}

// 解密
export function parseJwt(token) {
  const base64Url = token.split('.')[1];
  const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));

  return JSON.parse(jsonPayload);
}
